package com.example.springbootexceldemo.controller;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.springbootexceldemo.entity.Student;
import com.example.springbootexceldemo.utils.CExcelUtil;

import cn.hutool.poi.excel.ExcelWriter;

/**
 * Created on 2021-06-04
 */
@RestController
public class ExcelController {


    //resources/file/demo-explan.xlsx
    @PostMapping("/explainExcel")
    public Object explainExcel(@RequestPart("file") MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            System.out.println("empty");
            return 0;
        }
        //解析Excel
        List<List<Object>> datas = CExcelUtil.explainExcel(file.getInputStream(), 1);
        return datas;

    }


    @GetMapping("/downExcel")
    public void explainExcel(HttpServletResponse response) throws Exception {

        //查询数据库
        Student student = new Student(1, "张三", new Date());
        Student student2 = new Student(2, "李四", new Date());
        List<Object> datas = new ArrayList<>();
        datas.add(student);
        datas.add(student2);


        //设置对象属性和表头的对应关系
        LinkedHashMap headers = new LinkedHashMap<>();
        headers.put("id", "中文名");
        headers.put("name", "邮箱前缀");
        headers.put("birthday", "部门名");


        //创建Excel
        ExcelWriter writer = CExcelUtil.getExcelWriter(headers, datas);


        //设置response属性
        String name = "汉字";
        response.setContentType("application/ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition",
                String.format("attachment;filename=%s", URLEncoder.encode(name, "UTF-8") + ".xlsx"));

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);

        //关闭流
        writer.close();
        out.close();


    }


}
